import requests
import json
import os

APP_ID = "f5aba21d-41ab-4c32-ac84-13859c963dff"
AUTH_TOKEN = 'Bearer bce-v3/ALTAK-slayD7ZmGB9iKv4MlE6cw/a7c55550ae3887730adc960282cc1cf66b3300be'

def post_request(url, headers, payload=None, files=None):
    """发送 POST 请求并返回响应"""
    try:
        response = requests.post(url, headers=headers, json=payload, files=files)
        response.raise_for_status()  # 抛出 HTTPError
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP 错误: {http_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"请求失败: {req_err}")
    return None

def get_conversation_id():
    """获取 conversation_id"""
    url = "https://qianfan.baidubce.com/v2/app/conversation"
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': AUTH_TOKEN
    }
    payload = {'app_id': APP_ID}
    
    response = post_request(url, headers, payload)
    if response:
        return response.get('conversation_id')
    return None

def upload_file(conversation_id):
    """上传文件"""
    url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"
    headers = {
        'X-Appbuilder-Authorization': AUTH_TOKEN
    }
    
    file_path = r'D:\a-tool\1.jpg'
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return None

    with open(file_path, 'rb') as f:
        files = {
            'file': (os.path.basename(file_path), f, 'image/jpeg')
        }
        payload = {'app_id': APP_ID}
        response = post_request(url, headers, payload, files)
        return response

def run_conversation(conversation_id):
    """进行对话"""
    url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
    query = input("请输入问题：")
    payload = {
        "app_id": APP_ID,
        "query": query,
        "stream": False,
        "conversation_id": conversation_id
    }
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': AUTH_TOKEN
    }
    
    response = post_request(url, headers, payload)
    if response:
        print(json.dumps(response, ensure_ascii=False, indent=4))

def main():
    conversation_id = get_conversation_id()
    if conversation_id:
        upload_response = upload_file(conversation_id)
        if upload_response:
            print(json.dumps(upload_response, ensure_ascii=False, indent=4))  # 输出上传文件的响应
        run_conversation(conversation_id)
    else:
        print("未能获取 conversation_id，请检查配置和权限。")

if __name__ == '__main__':
    main()